<template>
    <view class="mx-40">
        <uv-form :model="formData" :rules="rules" ref="formRef" labelWidth="250rpx">
            <uv-form-item :required="true" label="乡镇名称" prop="TownCode" borderBottom @click="openPicker">
                <uv-input :readonly="true" v-model="formData.Town" placeholder="请选择乡镇" border="none"></uv-input>
                <template v-slot:right>
                    <uv-icon name="arrow-right"></uv-icon>
                </template>
            </uv-form-item>
            <uv-form-item :required="true" label="发生时间" prop="Fssj" borderBottom @click="dateConfirm">
                <uv-input :readonly="true" v-model="formData.Fssj" placeholder="请选择发生时间" border="none"></uv-input>
                <template v-slot:right>
                    <uv-icon name="arrow-right"></uv-icon>
                </template>
            </uv-form-item>

            <uv-form-item label="地理位置" prop="Place" labelPosition="top" borderBottom>
                <uv-textarea customStyle="margin-top: 20rpx;" v-model="formData.Place"
                    placeholder="请选择地理位置"></uv-textarea>
                <template v-slot:right>
                    <uv-icon @click="getLocation" size="40rpx" color="#547ff7" name="map-fill"></uv-icon>
                </template>
            </uv-form-item>
            <uv-form-item :required="true" label="经度/纬度" prop="LonLat" borderBottom>
                <uv-input :readonly="true" v-model="formData.LonLat" placeholder="请选择经度/纬度" border="none"></uv-input>
                <template v-slot:right>
                    <uv-image @click="getLocation" src="/static/img/map/dingwei.svg" width="50rpx"
                        height="50rpx"></uv-image>
                </template>
            </uv-form-item>
            <uv-form-item :required="true" label="地质灾害类型" prop="Zhlx" borderBottom>
                <uv-radio-group v-model="formData.Zhlx" :customStyle="{ width: '100%' }">
                    <uv-radio :customStyle="{
                        margin: '0rpx 40rpx 20rpx 0',
                        width: '40%',
                    }" size="28rpx" labelSize="28rpx" v-for="(item, index) in dzzhList" :key="index" :label="item.name"
                        :name="item.value"></uv-radio>
                </uv-radio-group>
            </uv-form-item>
            <uv-form-item :required="true" label="是否在1:10000中高分险区" prop="Gfxq" borderBottom>
                <uv-radio-group v-model="formData.Gfxq">
                    <uv-radio :customStyle="{
                        margin: '0rpx 50rpx 0rpx 0',
                    }" size="28rpx" labelSize="28rpx" v-for="(item, index) in radiolist" :key="index"
                        :label="item.name" :name="item.value"></uv-radio>
                </uv-radio-group>
            </uv-form-item>
            <uv-form-item :required="true" label="是否为切坡建房点" prop="Qpjf" borderBottom>
                <uv-radio-group v-model="formData.Qpjf">
                    <uv-radio size="28rpx" labelSize="28rpx" :customStyle="{
                        margin: '0rpx 50rpx 0rpx 0',
                    }" v-for="(item, index) in radiolist" :key="index" :label="item.name"
                        :name="item.value"></uv-radio>
                </uv-radio-group>
            </uv-form-item>
            <uv-form-item :required="true" label="是否为成功避险" prop="Cgbr" borderBottom>
                <uv-radio-group v-model="formData.Cgbr">
                    <uv-radio size="28rpx" labelSize="28rpx" :customStyle="{
                        margin: '0rpx 50rpx 0rpx 0',
                    }" v-for="(item, index) in radiolist" :key="index" :label="item.name"
                        :name="item.value"></uv-radio>
                </uv-radio-group>
            </uv-form-item>
            <uv-form-item :required="true" label="是否在册隐患" prop="ZcYhd" borderBottom>
                <uv-radio-group v-model="formData.ZcYhd">
                    <uv-radio size="28rpx" labelSize="28rpx" :customStyle="{
                        margin: '0rpx 50rpx 0rpx 0',
                    }" v-for="(item, index) in radiolist" :key="index" :label="item.name"
                        :name="item.value"></uv-radio>
                </uv-radio-group>
            </uv-form-item>
            <uv-form-item :required="true" label="引发因素" prop="Yfys" borderBottom>
                <uv-radio-group v-model="formData.Yfys">
                    <uv-radio size="28rpx" labelSize="28rpx" :customStyle="{
                        margin: '0rpx 40rpx 0rpx 0',
                    }" v-for="(item, index) in yfysList" :key="index" :label="item.name" :name="item.value"></uv-radio>
                </uv-radio-group>
            </uv-form-item>
            <uv-form-item :required="true" label="填表人" prop="Tbr" borderBottom>
                <uv-input v-model="formData.Tbr" clearable placeholder="请输入填表人" border="none"></uv-input>
            </uv-form-item>
            <uv-form-item :required="true" label="情况说明" prop="Remark" labelPosition="top" borderBottom>
                <uv-textarea customStyle="margin-top: 20rpx;" v-model="formData.Remark"
                    placeholder="填写情况说明"></uv-textarea>
            </uv-form-item>
            <uv-form-item label="速报照片" prop="FileIds" border="none" labelPosition="top">
                <lh-upload-img :list="formData.FileIds" :mount="3" :formData="uploadFormData"
                    @change="updateFile"></lh-upload-img>
            </uv-form-item>
        </uv-form>
        <uv-button type="primary" v-if="formOperType != SYSFORMOPERTYPE.View" @click="submitForm"
            :loading="loading">提交报表</uv-button>
        <uv-gap height="60rpx"></uv-gap>
    </view>
    <!-- 选择器 -->
    <uv-picker round="40rpx" ref="pickerRef" :columns="[townOptions]" keyName="text"
        @confirm="pickerConfirm"></uv-picker>

    <uv-datetime-picker round="40rpx" ref="datetimePicker" v-model="dateValue" mode="datetime"
        @confirm="PickerConfirm"></uv-datetime-picker>
</template>

<script lang="ts" setup>
import { useTownOptions } from '@/hooks/useOptions';
import { addZqsb_API, GetZqsbDetail_API, updageZqsb_API } from '@/server/home';
import { useUserStore } from '@/stores';
import { SYSFORMOPERTYPE } from '@/utils/enum';
import dayjs from 'dayjs';
const storeUser = useUserStore()

let sbdId = ''
const formOperType = ref()
onLoad((e) => {
    sbdId = e.id
    formOperType.value = e.optype || SYSFORMOPERTYPE.Add;
    if (sbdId) initTask()
})
const rules = {
    TownCode: {
        required: true,
        message: '请选择乡镇',
        trigger: ['change', 'blur']
    },
    Fssj: {
        required: true,
        message: '请选择发生时间',
        trigger: ['change', 'blur']
    },
    LonLat: {
        required: true,
        message: '请输入经纬度',
        trigger: ['change', 'blur']
    },
    Lon: [{
        required: true,
        message: '请输入经度',
        trigger: ['change', 'blur']
    }, {
        validator: function (rule, value, callback) {
            let lonReg =
                /^-?(((\d|[1-9]\d|1[0-7]\d|0)\.\d{0,16})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,16}|180)$/i;
            if (!lonReg.test(value)) {
                callback('请输入正确的经度')
            }
            return true
        },
        message: '请输入正确的经度',
        trigger: ['change', 'blur']
    }],
    Lat: {
        rules: [{
            required: true,
            errorMessage: '请输入纬度',
            trigger: ['change', 'blur']
        }, {
            validator: function (rule, value, data, callback) {
                let latReg = /^-?([0-8]?\d{1}\.\d{0,16}|90\.0{0,16}|[0-8]?\d{1}|90)$/i;
                if (!latReg.test(value)) {
                    callback('请输入正确的经度')
                }
                return true
            },
            message: '请输入正确的经度',
            trigger: ['change', 'blur']
        }]
    },
    Fsgm: {

        required: true,
        message: '请输入发生规模'

    },
    Jjss: {
        required: true,
        message: '请输入经济损失'
    },
    Wxcc: {
        required: true,
        message: '请输入威胁财产'
    },
    Zhlx: {
        required: true,
        message: '请选择地质灾害类型'
    },
    Gfxq: {
        required: true,
        message: '请选择是否在1:10000中高分险区'
    },
    Qpjf: {
        required: true,
        message: '请选择是否为切坡建房点'
    },
    Cgbr: {
        required: true,
        message: '请选择是否为成功避险'
    },
    ZcYhd: {
        required: true,
        message: '请选择是否在册隐患'
    },
    Yfys: {
        required: true,
        message: '请选择引发因素'
    },
    Tbr: {
        required: true,
        message: '请输入填表人'
    },
    Remark: {
        required: true,
        message: '请输入情况说明'
    }
}
const formData = ref({
    TownCode: '',
    Town: '',
    Place: '',
    Lon: 112.984549,
    Lat: 28.057749,
    Fssj: null,
    Fsgm: 0,
    yhgm: 0,
    Ssrs: 0,
    Swrs: 0,
    Jjss: 0,
    shfw: 0,
    shtd: 0,
    Wxhs: 0,
    Wxrs: 0,
    Wxcc: 0,
    Cgbr: '',
    Tbr: '',
    Remark: '',
    FileIds: [],
    Zhlx: '',
    Gfxq: '',
    Qpjf: '',
    ZcYhd: '',
    Yfys: '',
    LonLat: '1',

})
const { townOptions, fetchTownOptions } = useTownOptions()
const pickerRef = ref()
const openPicker = async () => {
    await fetchTownOptions()
    pickerRef.value?.open()
}
const pickerConfirm = (e) => {
    console.log("e:", e);
    formData.value.Town = e.value[0].text
    formData.value.TownCode = e.value[0].value
}
const dateValue = ref(Number(new Date()))
const datetimePicker = ref()
const dateConfirm = () => {
    datetimePicker.value?.open()
    dateValue.value = formData.value.Fssj ? dayjs(formData.value.Fssj).valueOf() : Number(new Date())
}
const PickerConfirm = (e) => {
    const data = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
    formData.value.Fssj = data
}

const getLocation = () => {
    uni.showLoading({
        title: "定位中",
    })
    uni.getLocation({
        type: 'gcj02',
        geocode: true,
        isHighAccuracy: true,
        success: (res) => {
            console.log('当前位置：', res);
            formData.value.Lon = res.longitude;
            formData.value.Lat = res.latitude;
            formData.value.LonLat = Number(res.longitude).toFixed(6) + '/' + Number(res.latitude).toFixed(6);
            if (res.address) {
                formData.value.Place = res.address?.province + res.address?.city + res.address
                    ?.district + res.address?.street + res.address?.streetNum + res.address?.poiName
            }
        },
        fail(err) {
            uni.showToast({
                title: "获取位置失败",
            })
        },
        complete: () => {
            uni.hideLoading()
        },
    });
}

const dzzhList = [
    { name: "崩塌", value: 1 },
    { name: "泥石流", value: 2 },
    { name: "地面塌陷", value: 3 },
    { name: "其他", value: 4 },
]
const radiolist = [
    { name: "是", value: 1 },
    { name: "否", value: 0 },
]
const yfysList = [
    { name: "自然因素", value: 0 },
    { name: "人为因素", value: 1 }
]

const uploadFormData = ref({
    TypeCode: "ZQSB",
    FKey: storeUser.userInfo.AdminCode,
})
const updateFile = (e) => {
    formData.value.FileIds = e
}
const loading = ref()
const formRef = ref()
const submitForm = async () => {
    try {
        await formRef.value.validate();
        loading.value = true
        if (formData.value.FileIds.length == 0) {
            formData.value.FileIds = null;
        }
        let res
        if (formOperType.value == SYSFORMOPERTYPE.Edit) {
            res = await updageZqsb_API(formData.value, sbdId)
        } else {
            res = await addZqsb_API(formData.value)
        }
        if (res.IsSuccess) {
            uni.$uv.toast("提交成功")
            // uni.$emit('refresh-data')
            setTimeout(() => {
                loading.value = false;
                uni.navigateBack()
            }, 1000)
        } else {
            uni.$uv.toast(res.Message || '提交失败')
        }
    } catch (error) {
        loading.value = false;
    }
}

const initTask = async () => {
    const res = await GetZqsbDetail_API(sbdId)
    if (res.IsSuccess) {
        formData.value = res.Data
        uploadFormData.value.FKey = res.Data.Id
        formData.value.LonLat = Number(res.Data.Lon).toFixed(6) + '/' + Number(res.Data.Lat).toFixed(6);
    }
}
</script>

<style lang="scss" scoped></style>
